import sys
import subprocess
import threading
import logging

from PySide6.QtCore import QObject, Slot, Signal
from PySide6.QtWidgets import QApplication
from PySide6.QtQml import QQmlApplicationEngine

# ============ 日志配置 ============
logging.basicConfig(
    level=logging.DEBUG,  # 输出 DEBUG 及以上级别
    format="[%(asctime)s] [%(levelname)s] %(name)s: %(message)s",
    datefmt="%H:%M:%S"
)
logger = logging.getLogger("LogcatBackend")


class LogcatBackend(QObject):
    # 可以给 QML 发送信号，比如把日志行传过去
    logLine = Signal(str)

    def __init__(self):
        super().__init__()
        self.proc = None
        self.stop_event = threading.Event()
        logger.debug("LogcatBackend 初始化完成")

    @Slot()
    def logcatStart(self):
        if self.proc:
            logger.warning("logcat 已经在运行，忽略启动请求")
            return

        self.stop_event.clear()
        logger.info("准备启动 adb logcat")

        def run():
            cmd = ["adb", "logcat", "*:D"]
            try:
                self.proc = subprocess.Popen(
                    cmd,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    text=True,
                    bufsize=1  # 行缓冲
                )
                logger.info("adb logcat 子进程已启动 (pid=%s)", self.proc.pid)

                for line in self.proc.stdout:
                    if self.stop_event.is_set():
                        logger.info("检测到 stop_event，终止 logcat")
                        self.proc.terminate()
                        break

                    line = line.rstrip()
                    if line:
                        logger.debug("收到日志: %s", line[:120])  # 避免太长
                        self.logLine.emit(line)  # 发信号给 QML
            except FileNotFoundError:
                logger.error("未找到 adb，请检查 PATH 或指定 adb 路径")
            except Exception as e:
                logger.exception("logcat 运行时出错: %s", e)
            finally:
                self.proc = None
                logger.info("logcat 子进程退出")

        threading.Thread(target=run, daemon=True).start()

    @Slot()
    def logcatStop(self):
        if not self.proc:
            logger.warning("logcat 没有运行，忽略 stop 请求")
            return

        logger.info("请求停止 logcat")
        self.stop_event.set()

    @Slot()
    def clearLog(self):
        logger.info("请求清空日志")
        self.logLine.emit("")  # QML 可以连接这个信号清空 TextArea


if __name__ == "__main__":
    logger.info("程序启动中...")
    app = QApplication(sys.argv)
    engine = QQmlApplicationEngine()

    backend = LogcatBackend()
    engine.rootContext().setContextProperty("python", backend)

    engine.load("main.qml")
    if not engine.rootObjects():
        logger.critical("QML 加载失败，程序退出")
        sys.exit(-1)

    logger.info("进入 Qt 事件循环")
    sys.exit(app.exec())
